package cn.tedu.order.tx;

import cn.tedu.order.entity.Order;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.UUID;

// 用新的业务类，代替 OrderServiceImpl
@Service
@Slf4j
public class TxOrderService implements OrderService {
    @Autowired
    private RocketMQTemplate rmt;

    @Override
    public void create(Order order) {
        String xid = UUID.randomUUID().toString().replaceAll("-", "");
        // 不直接存储订单
        // 而是发送事务消息
        AccountMessage am = new AccountMessage(order.getUserId(),order.getMoney(),xid);
        String json = JsonUtil.to(am);
        // 把 json 封装成 spring 通用的 Message 对象
        Message<String> msg = MessageBuilder.withPayload(json).build();
        // Topic:Tag
        rmt.sendMessageInTransaction("order-topic", msg, order); // 第三个参数是传给监听器的业务数据
        log.info("事务消息处理完成");
    }
}
